/*
 * Copyright 2011 Christoph Ludwig (christoph[at]chludwig.de). All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package de.chludwig.ehumanities.provenance.resources;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.chludwig.ehumanities.provenance.entities.Archive;
import de.chludwig.ehumanities.provenance.exception.ProvenanceException;
import de.chludwig.ehumanities.provenance.exception.ProvenanceFileNotFoundException;

/**
 * Represents a zipped archive.
 */
@Path("/ziparchive/{archiveId}")
public class ZipArchiveResource {

  public static final String APPLICATION_ZIP = "application/zip";

  public static final MediaType APPLICATION_ZIP_TYPE = MediaType.valueOf(APPLICATION_ZIP);

  private static final Logger LOG = LoggerFactory.getLogger(ZipArchiveResource.class);
  
  private Archive archive;

  /**
   * @return the archive
   */
  public Archive getArchive() {
    return archive;
  }

  /**
   * @param archive
   *          the archive to set
   */
  protected void setArchive(Archive archive) {
    this.archive = archive;
  }

  /**
   * @param archive
   *          the archive to set
   */
  protected void setZipArchive(UUID archiveId) {
    setArchive(Archive.archiveWithId(archiveId));
  }

  @GET
  @Produces(APPLICATION_ZIP)
  public File deliverArchive(@PathParam("archiveId") UUID archiveId) {
    setZipArchive(archiveId);
    Archive zippedArchive = getArchive();
    File result;
    try {
      result = zippedArchive.getZipFile();
    }
    catch (IOException ex) {
      String msg = "zip file for archive " + archiveId + " not found";
      ProvenanceException notFound = new ProvenanceFileNotFoundException(msg, ex);
      LOG.info("Zip archive {} not found", archiveId, notFound);
      throw notFound;
    }
    return result;
  }
}
